package com.kingmed.kmss.framework.feign.client.kmcs;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpStatus;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.kingmed.kmss.common.dto.kmcs.*;
import com.kingmed.kmss.common.exception.external.ExternalApiException;
import com.kingmed.kmss.common.vo.CommonPage;
import feign.Response;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * 集成外围接口后，二次封装
 */
@Slf4j
@Component
public class LbFeignServiceFacade {

    @Autowired
    private LbFeignService lbFeignService;

    /**
     * 子公司获取默认实验室
     */
    public List<PsDefaultLabDTO> getDefaultLab(PsQueryDTO queryDTO) {
        List<PsDefaultLabDTO> result = new ArrayList<>();
        try {
            PsQueryDTO psQueryDTO = new PsQueryDTO();
            psQueryDTO.setOrgCode(queryDTO.getOrgCode());
            Response response = lbFeignService.defaultLab(psQueryDTO);
            if (response != null && response.status() == HttpStatus.HTTP_OK) {
                JSONObject jsonObject = JSONUtil.parseObj(IOUtils.toString(response.body().asInputStream(), StandardCharsets.UTF_8.toString()));
                JSONArray jsonArray = jsonObject.getJSONArray("result");
                if (jsonArray != null) {
                    jsonArray.forEach(item -> {
                        PsDefaultLabDTO mpDTO = JSONUtil.toBean(JSONUtil.toJsonStr(item), PsDefaultLabDTO.class);
                        if (mpDTO != null) {
                            result.add(mpDTO);
                        }
                    });
                }
            }
            return result;
        } catch (Exception e) {
            log.error("实验室-子公司获取默认实验室-异常：" + e.getMessage());
            throw new ExternalApiException("实验室-子公司获取默认实验室-异常" + e.getMessage());
        }
    }

    /**
     * 实验室检测项目ID获取指定外包方实验室列表
     */
    public List<PsOutLabDTO> getOutLab(PsQueryDTO queryDTO) {
        List<PsOutLabDTO> result = new ArrayList<>();
        try {
            PsQueryDTO psQueryDTO = new PsQueryDTO();
            psQueryDTO.setTestItemId(queryDTO.getTestItemId());
            psQueryDTO.setOrgCode(queryDTO.getOrgCode());
            Response response = lbFeignService.outLab(psQueryDTO);
            if (response != null && response.status() == HttpStatus.HTTP_OK) {
                JSONObject jsonObject = JSONUtil.parseObj(IOUtils.toString(response.body().asInputStream(), StandardCharsets.UTF_8.toString()));
                JSONArray jsonArray = jsonObject.getJSONArray("result");
                if (jsonArray != null) {
                    jsonArray.forEach(item -> {
                        PsOutLabDTO mpDTO = JSONUtil.toBean(JSONUtil.toJsonStr(item), PsOutLabDTO.class);
                        if (mpDTO != null) {
                            result.add(mpDTO);
                        }
                    });
                }
            }
            return result;
        } catch (Exception e) {
            log.error("实验室-指定外包方实验室列表-异常：" + e.getMessage());
            throw new ExternalApiException("实验室-指定外包方实验室列表-异常" + e.getMessage());
        }
    }

    /**
     * 报告单模板列表
     */
    public CommonPage<PsReportTempDTO> getReportTemp(PsQueryDTO queryDTO) {
        CommonPage<PsReportTempDTO> pageDto = new CommonPage<>();
        List<PsReportTempDTO> result = new ArrayList<>();
        try {
            PsQueryDTO psQueryDTO = new PsQueryDTO();
            psQueryDTO.setPageSize(queryDTO.getPageSize());
            psQueryDTO.setPageNumber(queryDTO.getPageNumber());
            psQueryDTO.setBizOrgCode(queryDTO.getBizOrgCode());
            psQueryDTO.setReportModelName(queryDTO.getReportModelName());
            Response response = lbFeignService.reportTemp(psQueryDTO);
            if (response != null && response.status() == HttpStatus.HTTP_OK) {
                JSONObject jsonObject = JSONUtil.parseObj(IOUtils.toString(response.body().asInputStream(), StandardCharsets.UTF_8.toString()));
                JSONObject resultObj = jsonObject.getJSONObject("result");
                if (resultObj != null) {
                    String total = resultObj.getStr("totalElements");
                    pageDto.setTotal(total != null ? Long.parseLong(total) : 0L);

                    String totalPage = resultObj.getStr("totalPages");
                    pageDto.setTotalPage(totalPage != null ? Integer.parseInt(totalPage) : 0);

                    pageDto.setPageNo(Integer.parseInt(queryDTO.getPageNumber()));
                    pageDto.setPageSize(Integer.parseInt(queryDTO.getPageSize()));

                    JSONArray jsonArray = resultObj.getJSONArray("content");
                    if (jsonArray != null) {
                        jsonArray.forEach(item -> {
                            PsReportTempDTO mpDTO = JSONUtil.toBean(JSONUtil.toJsonStr(item), PsReportTempDTO.class);
                            if (mpDTO != null) {
                                result.add(mpDTO);
                            }
                        });
                    }
                }
            }
            pageDto.setList(result);
            return pageDto;
        } catch (Exception e) {
            log.error("实验室-报告单模板列表-异常：" + e.getMessage());
            throw new ExternalApiException("实验室-报告单模板列表-异常" + e.getMessage());
        }
    }

    /**
     * 实验室检测项目ID获取检测系统列表
     */
    public List<PsCheckSystemDTO> getCheckSystem(PsQueryDTO queryDTO) {
        List<PsCheckSystemDTO> result = new ArrayList<>();
        try {
            PsQueryDTO psQueryDTO = new PsQueryDTO();
            psQueryDTO.setTestItemIdList(queryDTO.getTestItemIdList());
            Response response = lbFeignService.checkSystem(psQueryDTO);
            if (response != null && response.status() == HttpStatus.HTTP_OK) {
                JSONObject jsonObject = JSONUtil.parseObj(IOUtils.toString(response.body().asInputStream(), StandardCharsets.UTF_8.toString()));
                JSONArray jsonArray = jsonObject.getJSONArray("result");
                if (jsonArray != null && jsonArray.size() > 0) {
                    JSONArray materialPlanList = JSONUtil.parseObj(jsonArray.get(0)).getJSONArray("materialPlanList");
                    if (materialPlanList != null) {
                        materialPlanList.forEach(item -> {
                            PsCheckSystemDTO dto = JSONUtil.toBean(JSONUtil.toJsonStr(item), PsCheckSystemDTO.class);
                            if (dto != null) {
                                dto.setTestSystemHeaderName(this.handleCheckSystemName(dto));
                                result.add(dto);
                            }
                        });
                    }
                }
            }
            return result;
        } catch (Exception e) {
            log.error("实验室-检测系统-异常：" + e.getMessage());
            throw new ExternalApiException("实验室-检测系统-异常" + e.getMessage());
        }
    }


    /**
     * 根据实验室检测项目ID获取结果单位列表
     */
    public List<PsResultDwDTO> getResultDw(List<String> testItemIdList) {
        List<PsResultDwDTO> result = new ArrayList<>();
        try {
            PsQueryDTO psQueryDTO = new PsQueryDTO();
            psQueryDTO.setTestItemIdList(testItemIdList);
            Response response = lbFeignService.resultDw(psQueryDTO);
            if (response != null && response.status() == HttpStatus.HTTP_OK) {
                JSONObject jsonObject = JSONUtil.parseObj(IOUtils.toString(response.body().asInputStream(), StandardCharsets.UTF_8.toString()));
                JSONArray jsonArray = jsonObject.getJSONArray("result");
                if (jsonArray != null && jsonArray.size() > 0) {
                    result = JSONUtil.toList(jsonArray, PsResultDwDTO.class);
                }
            }
            return result;
        } catch (Exception e) {
            log.error("实验室-获取结果单位列表-异常：" + e.getMessage());
            throw new ExternalApiException("实验室-获取结果单位列表-异常" + e.getMessage());
        }
    }


    private String handleCheckSystemName(PsCheckSystemDTO dto) {
        String testSystemCode = StrUtil.isBlank(dto.getTestSystemCode()) ? "0" : dto.getTestSystemCode();
        String equipmentModel = StrUtil.isBlank(dto.getEquipmentModel()) ? "0" : dto.getEquipmentModel();
        String equipmentName = StrUtil.isBlank(dto.getEquipmentName()) ? "0" : dto.getEquipmentName();
        String itemName = StrUtil.isBlank(dto.getItemName()) ? "0" : dto.getItemName();
        return testSystemCode.concat("+").concat(equipmentModel).concat("+").concat(equipmentName).concat("+").concat(itemName);
    }

}
